package com.google.code.mochaccino.framework.webstrap;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import ch.qos.logback.core.joran.spi.JoranException;
import com.google.code.mochaccino.framework.bootstrap.Bootstrap;
import com.google.code.mochaccino.framework.webstrap.jetty.JettyModule;
import com.google.inject.Injector;
import com.google.inject.Module;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Web Server Bootstrap */
public abstract class Webstrap extends Bootstrap {

	private static final Logger      logger     = LoggerFactory.getLogger( Webstrap.class );
	private              Server      server     = null;

	/** Constructor */
	public Webstrap( boolean keepAlive ) throws JoranException {
		super( keepAlive );
	}


	/** Provides the Guice Modules */
	protected final Module[] getModules() {
		List<Module> moduleList = new ArrayList<Module>();
		moduleList.add( new JettyModule( getConnectors() ) );
		Module[] appModules = getApplicationModules();
		if ( appModules != null ) {
			moduleList.addAll( Arrays.asList( appModules ) );
		}
		return moduleList.toArray( new Module[moduleList.size()] );
	}

	protected abstract Module[] getApplicationModules();


	@Override
	protected void doStop( Injector injector ) {
		try {
			server.stop();
		} catch ( Exception e ) {
			logger.error( e.getMessage(), e );
		}
	}

	@Override
	protected void interpretArgsAfterInjection( String[] args, Injector injector ) {
		SessionHandler sessionHandler = injector.getInstance( SessionHandler.class );
		server = injector.getInstance( Server.class );
		createServletContextHandlers( server, sessionHandler, injector );

		try {
			server.start();
		} catch ( Exception e ) {
			throw new RuntimeException( e );
		}
	}

	/** Create Servlet Context Handlers */
	protected abstract ServletContextHandler[] createServletContextHandlers( Server server, SessionHandler sessionHandler, Injector injector );

	/** Produce the Connectors for the Web Server */
	public abstract Connector[] getConnectors();

	@Override
	protected void interpretArgsBeforeInjection( String[] args ) {

	}
}
